﻿using AutoMapper.Execution;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Restful_Api.Helpers
{
    /// <summary>
    /// 用于接收一组key 来查询一组公司
    /// </summary>
    public class ArrayModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            //如果不是作用于Enumerable类型的参数
            if (!bindingContext.ModelMetadata.IsEnumerableType)
            {
                bindingContext.Result = ModelBindingResult.Failed();
                return Task.CompletedTask;
            }
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
            //为空 ModelBindingResult的绑定状态也是成功 因为只是没传递参数
            if (string.IsNullOrWhiteSpace(value))
            {
                bindingContext.Result = ModelBindingResult.Success(null);
                return Task.CompletedTask;
            }
            //通过反射获得类型
            var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
            var converter = TypeDescriptor.GetConverter(elementType);

            //截取，分割  并且过滤掉空的元素
            var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x=>converter.ConvertFromString(x.Trim())).ToArray();

            //(因为values为obj的数组)
            //创建一个类型为elementType的 长度为values 的新数组
            var typeValues = Array.CreateInstance(elementType, values.Length);
            //从第0个开始拷贝到新数组
            values.CopyTo(typeValues, 0);

            bindingContext.Model = typeValues;
            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            return Task.CompletedTask;
        }
    }
}
